<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="mini"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="运营状态" prop="operationalStatus">
        <el-select
          v-model="queryParams.operationalStatus"
          @change="handleQuery"
        >
          <el-option :value="'在线'">在线</el-option>
          <el-option :value="'离线'">离线</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="车辆类型" prop="carType">
        <el-select v-model="queryParams.carType" @change="handleQuery">
          <el-option :value="'砼车'">砼车</el-option>
          <el-option :value="'泵车'">泵车</el-option>
          <el-option :value="'铲车'">铲车</el-option>
          <el-option :value="'新华轩销售车'">新华轩销售车</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="车辆归属" prop="carAttribution">
        <el-select v-model="queryParams.carAttribution" @change="handleQuery">
          <el-option :value="'自有车辆'">自有车辆</el-option>
          <el-option :value="'定租车'">定租车</el-option>
          <el-option :value="'临时租赁'">临时租赁</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否有外派任务" prop="isDispatched">
        <el-select v-model="queryParams.isDispatched" @change="handleQuery">
          <el-option :value="true" label="是"></el-option>
          <el-option :value="false" label="否"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="车辆编号" prop="carNumber">
        <el-input
          v-model.trim="queryParams.carNumber"
          placeholder="请输入车辆编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="carLicensePlate">
        <el-input
          v-model.trim="queryParams.carLicensePlate"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="司机姓名" prop="driver">
        <el-input
          v-model.trim="queryParams.driver"
          placeholder="请输入司机姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['service:cars:add']"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="carsList"
      max-height="390"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="车辆ID" align="center" prop="id" fixed />
      <el-table-column
        label="车辆类型"
        align="center"
        prop="carType"
        min-width="160"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="车辆归属" align="center"  min-width="160" prop="carAttribution" />
      <el-table-column
        label="车辆编号"
        align="center"
        prop="carNumber"
        min-width="160"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="车牌照"
        align="center"
        prop="carLicensePlate"
        min-width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="品牌"
        align="center"
        prop="carBrand"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="车辆所有人"
        align="center"
        prop="carOwner"
        min-width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="核定载重量"
        align="center"
        prop="loadWeight"
        width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="泵送能力" align="center" prop="pumpingCapacity" />
      <el-table-column label="运营状态" align="center" prop="operationalStatus">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.operationalStatus"
            active-value="在线"
            disabled
            inactive-value="离线"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否外派" align="center" prop="isDispatched">
        <template slot-scope="scope">
          {{ scope.row.isDispatched ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="工作状态" align="center" prop="workingState" />
      <el-table-column label="司机姓名" align="center" prop="driverName" />
      <el-table-column
        label="最后编辑时间"
        align="center"
        prop="updateTime"
        width="160"
      >
        <template slot-scope="scope">
          {{ formatDate(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="300"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['service:cars:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-plus-outline"
            @click="handleBind(scope.row)"
            :disabled="!!scope.row.driverId"
            >绑定司机</el-button
          >
          <el-button
            size="mini"
            type="text"
            :disabled="!scope.row.driverId"
            icon="el-icon-remove-outline"
            @click="handleUnBind(scope.row)"
            >解绑司机</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <SelectNameDialog
      :dialogVisible="dialogVisible"
      :userType="2"
      @onClose="dialogVisible = false"
      @onSubmit="handleOnSubmit"
    ></SelectNameDialog>
    <!-- 添加或修改车辆基础信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="580px" append-to-body>
      <div class="fixed_dialog">
        <el-form ref="form" :model="form" :rules="rules" label-width="96px">
          <el-form-item label="车辆类型" prop="carType">
            <el-select
              v-model="form.carType"
              style="width: 100%"
              @change="handleCarType"
            >
              <el-option :value="'砼车'">砼车</el-option>
              <el-option :value="'泵车'">泵车</el-option>
              <el-option :value="'铲车'">铲车</el-option>
              <el-option :value="'新华轩销售车'">新华轩销售车</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="车辆归属" prop="carAttribution">
            <el-select v-model="form.carAttribution" style="width: 100%">
              <el-option :value="'自有车辆'">自有车辆</el-option>
              <el-option :value="'定租车'">定租车</el-option>
              <el-option :value="'临时租赁'">临时租赁</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="车辆编号" prop="carNumber">
            <el-input v-model="form.carNumber" placeholder="请输入车辆编号" />
          </el-form-item>
          <el-form-item label="车牌照" prop="carLicensePlate">
            <el-input
              v-model="form.carLicensePlate"
              placeholder="请输入车牌照"
            />
          </el-form-item>
          <el-form-item
            label="核定载重量"
            prop="loadWeight"
            :rules="
              pumpingCapacityRequired
                ? rules.loadWeight
                : [
                    {
                      required: false,
                      message: '请填写存在内容',
                      trigger: 'change',
                    },
                  ]
            "
          >
            <el-input
              :disabled="!pumpingCapacityRequired"
              v-model="form.loadWeight"
              placeholder="请输入核定载重量"
            />
          </el-form-item>
          <el-form-item
            label="泵送能力"
            prop="pumpingCapacity"
            :rules="
              loadWeightRequired
                ? rules.pumpingCapacity
                : [
                    {
                      required: false,
                      message: '请填写存在内容',
                      trigger: 'change',
                    },
                  ]
            "
          >
            <el-input
              :disabled="!loadWeightRequired"
              v-model="form.pumpingCapacity"
              placeholder="请输入泵送能力"
            >
              <template slot="append">米</template>
            </el-input>
          </el-form-item>
          <el-form-item label="品牌" prop="carBrand">
            <el-input v-model="form.carBrand" placeholder="请输入品牌" />
          </el-form-item>
          <el-form-item label="车辆所有人" prop="carOwner">
            <el-input v-model="form.carOwner" placeholder="请输入车辆所有人" />
          </el-form-item>
          <el-form-item label="运营状态" prop="carOwner">
            <el-switch
              @click.native="operationalStatusChange"
              :disabled="form.workingState !== '空闲中'"
              v-model="form.operationalStatus"
              active-value="在线"
              inactive-value="离线"
            ></el-switch>
          </el-form-item>
          <el-form-item label="车辆登记证" prop="registrationCards">
            <file-upload
              :isShowTip="false"
              v-model="form.registrationCards"
              :fileType="['png', 'jpg', 'jpeg']"
            ></file-upload>
          </el-form-item>
          <el-form-item label="车辆保险" prop="insurances">
            <file-upload
              :isShowTip="false"
              v-model="form.insurances"
              :fileType="['png', 'jpg', 'jpeg']"
            ></file-upload>
          </el-form-item>
          <template v-if="form.id">
            <el-form-item label="是否外派">
              <el-input
                v-model="isDispatch"
                :disabled="form.id"
                placeholder="请输入是否外派"
              />
            </el-form-item>
            <el-form-item label="工作状态">
              <el-input
                :disabled="form.id"
                v-model="form.workingState"
                placeholder="请输入工作状态"
              />
            </el-form-item>
            <el-form-item label="最后编辑时间">{{
              formatDate(form.updateTime)
            }}</el-form-item>
            <el-form-item label="创建时间">{{
              formatDate(form.createTime)
            }}</el-form-item>
          </template>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SelectNameDialog from "@/components/SelectDialog/SelectNameDialog";
import {
  listCars,
  getCars,
  delCars,
  addCars,
  updateCars,
  bindCars,
  unBindCars,
} from "@/api/service/cars";
import { formatDate } from "@/utils";
import { validateNumber } from "@/utils/validator";
export default {
  components: {
    SelectNameDialog,
  },
  name: "Cars",
  data() {
    return {
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车辆基础信息表格数据
      carsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        operationalStatus: null,
        carType: null,
        carAttribution: null, // 车辆归属
        isDispatched: null,
        carNumber: null,
        carLicensePlate: null,
        driver: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        carType: [
          { required: true, message: "车辆类型不能为空", trigger: "change" },
        ],
        carAttribution: [
          { required: true, message: "车辆归属不能为空", trigger: "blur" },
        ],
        carNumber: [
          { required: true, message: "车辆编号不能为空", trigger: "blur" },
        ],
        carLicensePlate: [
          { required: true, message: "车牌照不能为空", trigger: "blur" },
        ],
        loadWeight: validateNumber(),
        pumpingCapacity: validateNumber(),
        carBrand: [
          { required: true, message: "品牌不能为空", trigger: "blur" },
        ],
        carOwner: [
          { required: true, message: "车辆所有人不能为空", trigger: "blur" },
        ],
        operationalStatus: [
          { required: true, message: "运营状态不能为空", trigger: "change" },
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
        updateBy: [
          { required: true, message: "修改人不能为空", trigger: "blur" },
        ],
        updateTime: [
          { required: true, message: "修改时间不能为空", trigger: "blur" },
        ],
        isDispatched: [
          { required: true, message: "是否外派不能为空", trigger: "blur" },
        ],
        workingState: [
          { required: true, message: "工作状态不能为空", trigger: "blur" },
        ],
        insurances: [
          { required: true, message: "车辆保险不能为空", trigger: "blur" },
        ],
        registrationCards: [
          { required: true, message: "车辆登记证不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  watch: {
    "form.carType": {
      handler: function (n, o) {
        this.form.loadWeight = this.form.loadWeight || "";
        this.form.pumpingCapacity = this.form.pumpingCapacity || "";
      },
      deep: true,
    },
  },
  computed: {
    isDispatch() {
      return this.form.isDispatched ? "是" : "否";
    },
    pumpingCapacityRequired() {
      return !["泵车", "铲车", "新华轩销售车"].some(
        (s) => s === this.form.carType
      );
    },
    loadWeightRequired() {
      return !["砼车", "铲车", "新华轩销售车"].some(
        (s) => s === this.form.carType
      );
    },
  },
  methods: {
    formatDate,
    handleCarType() {
      this.form.loadWeight = null;
      this.form.pumpingCapacity = null;
    },
    handleUnBind(row) {
      this.$modal
        .confirm("确定解绑司机？")
        .then(function () {
          return unBindCars(row.id);
        })
        .then(() => {
          this.$modal.msgSuccess("解绑成功");
          this.getList();
        })
        .catch(() => {});
    },
    handleBind(row) {
      this.row = row;
      this.dialogVisible = true;
    },
    handleOnSubmit(userId) {
      bindCars(this.row.id, userId).then((res) => {
        this.$message.success("绑定司机成功");
        this.getList();
      });
    },
    formatDate,
    /** 查询车辆基础信息列表 */
    getList() {
      this.loading = true;
      listCars(this.queryParams).then((response) => {
        this.carsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        carType: null,
        carAttribution: null,
        carNumber: null,
        carLicensePlate: null,
        carBrand: null,
        carOwner: null,
        loadWeight: null,
        pumpingCapacity: null,
        operationalStatus: "离线",
        registrationCards: null,
        insurances: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDispatched: null,
        workingState: null,
        driverId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增车辆";
    },
    operationalStatusChange(value) {
      if (this.form.workingState !== "空闲中") {
        this.$message.error("当前车辆正在工作中，只能关闭状态为“空闲中");
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCars(id).then((response) => {
        this.form = {
          ...this.form,
          ...response.data,
        };
        // if(this.form)
        this.open = true;
        this.title = "修改车辆";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCars(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCars({
              ...this.form,
            }).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("删除车辆将解绑与司机的绑定关系")
        .then(function () {
          return delCars(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "service/cars/export",
        {
          ...this.queryParams,
        },
        `cars_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
